*****************************************************************************************************************************************************************
*REGRUNNER --- loop through various specifications/samples and save regression coefficients estimates (and other stats) for each as one line of dataset.
*****************************************************************************************************************************************************************

**SYNTAX: regrunner <reg specs>, runs{<runlist>} coeffs{<coefflist>} stats{<statlist>} dataout{<filepath>} fileout{<filepath>} sheetout{<sheetname>} option

*regspecs - usual regression specification but replace `x' with /x\ and ${z} with @{z}  [globals should be defined before running program, locals are specified in runlist]
*runlist -  name1[version1 version2...] name1[version1 version2...] ...  (MAX OF 10 names)  these specify versions of the regression (similar to listing elements to loop through and then calling the elements later using a local)
*----------New feature: locals /x\ and globals @{z} can be called within the version list (so long as they refer to a previous element of the runlist)
*coefflist - name[variablereference] name[variablereference]... this specifies the coefficients to save
*statlist - name[stat, command producing stat] name[stat, command producing stat] ...  this specifies the stats to save, anything that only requires 1 line of code and can be called with r().
*option - "loud" displays diagnostics, "silent" does not display regression or stat results, "force" will push through data/regression errors, "dry" saves dry run results dataset (just specifications without actual results)
/*EXAMPLE
*regrunner "reg /y\ i.bd_gtc_wi##c.z if inrange(bd,@{L/m\c1993},@{F/m\c1993}) & /y\!=. @{/pop\}, cluster(my)", ///
>                 runs{y[nsc_rec sdr_drop] pop[frl nofrl] m[6]} ///
>                 coeffs{gtc[1.bd_gtc_windows] gtz_z[1.bd_gtc_windows#c.z]} ///
>                 stats{mean[r(mean), summ /y\ if e(sample)] sd[r(sd), summ /y\ if e(sample)]} ///
>                 dataout{test} fileout{testxls} sheetout{testsh} silent
*/
capture program drop regrunner
program regrunner
	set more off
	gettoken reg0 0 : 0 , parse(",")
	local 0 = subinstr("`0'",",","",1)
	
	*Deal with problem characters ([,])
	local 0 = subinstr("`0'","\[","%%_",.)
	local 0 = subinstr("`0'","\]","_%%",.)
	
	*********Pull Out Options***
	local find = regexm("`0'","runs\{(.*)\} +coeffs\{(.*)\} +stats\{(.*)\} +dataout\{(.*)\} +fileout\{(.*)\} +sheetout\{(.*)\}(.*)")
	local ops = regexs(7)
	
	local q = "qui"
	local q2 = ""
	local force = ""
	local dry = 0
	
	if strmatch("`ops'","*loud*") local q = ""
	if strmatch("`ops'","*silent*") local q2 = "qui"
	if strmatch("`ops'","*force*") local force = "capture"
	if strmatch("`ops'","*dry*") {
		local force = "capture"
		local dry = 1
	}
	if strmatch("`ops'","*noxls*") local xls = "no"
	
	`q' di "1"
	if `find'==0 {
		di "ERROR: SYNTAX PROBLEM" as error
		exit
	}
	*local runs = subinstr(subinstr(regexs(0),"runs{","",1),"}","",1)
	local runs = regexs(1)
	local coeffs = regexs(2)
	local stats = regexs(3)
	*local other = regexs(4)
	`q' di "2"
	
	*local find = regexm("`other'","(dataout\{)(.*)(\} fileout\{)(.*)(\} sheetout\{)(.*)(\})(.*)")
	local dataout = regexs(4)
	local fileout = regexs(5)
	local sheetout = regexs(6)
	
	`q' di "3"
	
	`q' di "*************************************************************"
	`q' di "**********************DIAGNOSTIC*****************************"
	`q' di "*************************************************************"
	`q' di "reg0: `reg0'"
	`q' di "runs: `runs'"
	`q' di "coeffs: `coeffs'"
	`q' di "stats: `stats'"
	`q' di "dataout: `dataout'"
	`q' di "fileout: `fileout'"
	`q' di "sheetout: `sheetout'"
	`q' di "ops: `ops'"
	
	
	`q' di "********PARSE RUNS**********"
		local j=1
		local runs0 = "`runs'"
		while strmatch("`runs0'","*[*") {
			gettoken v`j' runs0 : runs0 , parse("[")
			local runs0 = subinstr("`runs0'","[","",1)
			gettoken vs`j' runs0 : runs0 , parse("]")
			local runs0 = subinstr("`runs0'","]","",1)
			`q' di "`v`j'': `vs`j''"
			local vall = "`vall' `v`j''"
			local vall_post0 = `"`vall_post0' ("/`v`j''\")"'
			local j= `j'+1
		}
		local NN = `j'
		forvalues j =`NN'/10 {
			local v`j' = "XXX"
			local vs`j' = "XXX"
			*di "`v`j'': `vs`j''"
		}
	
	`q' di "********PARSE COEFFS**********"
	local j=1
	local coeffs0 = "`coeffs'"
	while strmatch("`coeffs0'","*[*") {
		gettoken cn`j' coeffs0 : coeffs0 , parse("[")
		local coeffs0 = subinstr("`coeffs0'","[","",1)
		gettoken ci`j' coeffs0 : coeffs0 , parse("]")
		local coeffs0 = subinstr("`coeffs0'","]","",1)
		`q' di "`cn`j'': `ci`j''"
		local cnall = "`cnall' b_`cn`j'' se_`cn`j''"
		local cnall_post0 = `"`cnall_post0' (_b[`ci`j'']) (_se[`ci`j''])"'
		local j= `j'+1
	}
	local Nc = `j'-1
	
	`q' di "********PARSE STATS**********"
	local j=1
	local stats0 = "`stats'"
	while strmatch("`stats0'","*[*") {
		gettoken sn`j' stats0 : stats0 , parse("[")
		local stats0 = subinstr("`stats0'","[","",1)
		gettoken si`j' stats0 : stats0 , parse(",")
		local stats0 = subinstr("`stats0'",",","",1)
		gettoken sc`j' stats0 : stats0 , parse("]")
		local stats0 = subinstr("`stats0'","]","",1)
		local sc`j' = subinstr("`sc`j''","]","",1)
		
		*Put in brackets
		local sc`j' = subinstr("`sc`j''","%%_","[",.)
		local sc`j' = subinstr("`sc`j''","_%%","]",.)
		local si`j' = subinstr("`si`j''","%%_","[",.)
		local si`j' = subinstr("`si`j''","_%%","]",.)
		
		`q' di "`sn`j'': `sc`j''  -->  `si`j''"
		local snall = "`snall' `sn`j''"	
		local j= `j'+1
	}
	local Ns = `j'-1


	******TEMP FILE SETUP*******
	`force' tempname memhold	//	where you temporarily hold the postings
	if `dry'==1 tempname memhold_dry
	*`force' tempfile rdest		//	name of the temporary file that will become the new dataset
	`q' di "********OUTPUT FILE SETUP*********"
	`q' di "*Versions: `vall'"
	`q' di "*Coeffs: `cnall'"
	`q' di "*Stats: `snall'"
	`q' di "*POST-- str50(`vall') `cnall' `snall' obs str500(command)"
	if `dry'!=1 `force' postfile `memhold' str30(`vall') `cnall' `snall' obs str25(datetime) str750(command) using `dataout', replace	// this line is where you define the structure of the new dataset (i.e., how many vars, their names, and their types)
	if `dry'==1   postfile `memhold_dry' str30(`vall') str25(datetime) str750(command) using `dataout'_DRY, replace

	local j = 1
	`q' disp "`v`j'' -- `vs`j''"

	foreach vi`j' of local vs`j' {
		local j = 1
		`q' di "`j': `v`j'' = `vi`j''"
		local j1 = 2
		local vs`j1'_final = "`vs`j1''"
		forvalues jj = 1/`j'{
			local vs`j1'_final = subinstr("`vs`j1'_final'","/`v`jj''\", "`vi`jj''",.)
		}
		`q' disp "`j1' -- `v`j1'' -- `vs`j1'' -- `vs`j1'_final'"
		local vs`j1'_final = subinstr("`vs`j1'_final'","@","$",.)
		`q' disp "----> `vs`j1'_final'"
		local vs`j1'_final = "`vs`j1'_final'"
		local j =  `j1'
			
			foreach vi`j' of local vs`j'_final {
				local j = 2
				`q' di "`j': `v`j'' = `vi`j''"
				local j1 = 3
				local vs`j1'_final = "`vs`j1''"
				forvalues jj = 1/`j'{
					local vs`j1'_final = subinstr("`vs`j1'_final'","/`v`jj''\", "`vi`jj''",.)
				}
				`q' disp "`j1' -- `v`j1'' -- `vs`j1'' -- `vs`j1'_final'"
				local vs`j1'_final = subinstr("`vs`j1'_final'","@","$",.)
				`q' disp "----> `vs`j1'_final'"
				local vs`j1'_final = "`vs`j1'_final'"
				local j =  `j1'
				
				foreach vi`j' of local vs`j'_final {
					local j = 3
					`q' di "`j': `v`j'' = `vi`j''"
					local j1 = 4
					local vs`j1'_final = "`vs`j1''"
					forvalues jj = 1/`j'{
						local vs`j1'_final = subinstr("`vs`j1'_final'","/`v`jj''\", "`vi`jj''",.)
					}
					`q' disp "`j1' -- `v`j1'' -- `vs`j1'' -- `vs`j1'_final'"
					local vs`j1'_final = subinstr("`vs`j1'_final'","@","$",.)
					`q' disp "----> `vs`j1'_final'"
					local vs`j1'_final = "`vs`j1'_final'"
					local j =  `j1'
					
						foreach vi`j' of local vs`j'_final {
							local j = 4
							`q' di "`j': `v`j'' = `vi`j''"
							local j1 = 5
							local vs`j1'_final = "`vs`j1''"
							forvalues jj = 1/`j'{
								local vs`j1'_final = subinstr("`vs`j1'_final'","/`v`jj''\", "`vi`jj''",.)
							}
							`q' disp "`j1' -- `v`j1'' -- `vs`j1'' -- `vs`j1'_final'"
							local vs`j1'_final = subinstr("`vs`j1'_final'","@","$",.)
							`q' disp "----> `vs`j1'_final'"
							local vs`j1'_final = "`vs`j1'_final'"
							local j =  `j1'
							
							foreach vi`j' of local vs`j'_final {
								local j = 5
								`q' di "`j': `v`j'' = `vi`j''"
								local j1 = 6
								local vs`j1'_final = "`vs`j1''"
								forvalues jj = 1/`j'{
									local vs`j1'_final = subinstr("`vs`j1'_final'","/`v`jj''\", "`vi`jj''",.)
								}
								`q' disp "`j1' -- `v`j1'' -- `vs`j1'' -- `vs`j1'_final'"
								local vs`j1'_final = subinstr("`vs`j1'_final'","@","$",.)
								`q' disp "----> `vs`j1'_final'"
								local vs`j1'_final = "`vs`j1'_final'"
								local j =  `j1'
								
								foreach vi`j' of local vs`j'_final {
									local j = 6
									`q' di "`j': `v`j'' = `vi`j''"
									local j1 = 7
									local vs`j1'_final = "`vs`j1''"
									forvalues jj = 1/`j'{
										local vs`j1'_final = subinstr("`vs`j1'_final'","/`v`jj''\", "`vi`jj''",.)
									}
									`q' disp "`j1' -- `v`j1'' -- `vs`j1'' -- `vs`j1'_final'"
									local vs`j1'_final = subinstr("`vs`j1'_final'","@","$",.)
									`q' disp "----> `vs`j1'_final'"
									local vs`j1'_final = "`vs`j1'_final'"
									local j =  `j1'
									
									foreach vi`j' of local vs`j'_final {
										local j = 7
										`q' di "`j': `v`j'' = `vi`j''"
										local j1 = 8
										local vs`j1'_final = "`vs`j1''"
										forvalues jj = 1/`j'{
											local vs`j1'_final = subinstr("`vs`j1'_final'","/`v`jj''\", "`vi`jj''",.)
										}
										`q' disp "`j1' -- `v`j1'' -- `vs`j1'' -- `vs`j1'_final'"
										local vs`j1'_final = subinstr("`vs`j1'_final'","@","$",.)
										`q' disp "----> `vs`j1'_final'"
										local vs`j1'_final = "`vs`j1'_final'"
										local j =  `j1'
										
										foreach vi`j' of local vs`j'_final {
											local j = 8
											`q' di "`j': `v`j'' = `vi`j''"
											local j1 = 9
											local vs`j1'_final = "`vs`j1''"
											forvalues jj = 1/`j'{
												local vs`j1'_final = subinstr("`vs`j1'_final'","/`v`jj''\", "`vi`jj''",.)
											}
											`q' disp "`j1' -- `v`j1'' -- `vs`j1'' -- `vs`j1'_final'"
											local vs`j1'_final = subinstr("`vs`j1'_final'","@","$",.)
											`q' disp "----> `vs`j1'_final'"
											local vs`j1'_final = "`vs`j1'_final'"
											local j =  `j1'
											
											foreach vi`j' of local vs`j'_final {
												local j = 9
												`q' di "`j': `v`j'' = `vi`j''"
												local j1 = 10
												local vs`j1'_final = "`vs`j1''"
												forvalues jj = 1/`j'{
													local vs`j1'_final = subinstr("`vs`j1'_final'","/`v`jj''\", "`vi`jj''",.)
												}
												`q' disp "`j1' -- `v`j1'' -- `vs`j1'' -- `vs`j1'_final'"
												local vs`j1'_final = subinstr("`vs`j1'_final'","@","$",.)
												`q' disp "----> `vs`j1'_final'"
												local vs`j1'_final = "`vs`j1'_final'"
												local j =  `j1'
												
												foreach vi`j' of local vs`j'_final {
													local j = 10

													`q' di "`j': `v`j'' = `vi`j''"
													
													`q' di "****** Versions *******"
													`q' di `"`vall_post0'"'
													local vall_post_final = `"`vall_post0'"'
													forvalues jj = 1/10 {
														local vall_post_final = subinstr(`"`vall_post_final'"',"/`v`jj''\","`vi`jj''",.)
													}
													
													`q' di `"`vall_post_final'"'
													
													
													`q' di "****** REG *******"
													local reg_final = "`reg0'"
													forvalues jj = 1/10 {
														local reg_final = subinstr("`reg_final'","/`v`jj''\", "`vi`jj''",.)
													}
													local reg_final = subinstr("`reg_final'","@","$",.)
													`q' di `"`reg_final'"'
													
													`force' `q2'  `reg_final'
													
													`force' local obs = e(N)
													`force' local command=e(cmdline)
													if "`force'"!="capture" di `" `command' "'
																								
													
													`q' di "****** COEFFS *******"
													`q' di "`cnall_post0'"
													local cnall_post_final = "`cnall_post0'"
													forvalues jj =1/10 {
														local cnall_post_final = subinstr("`cnall_post_final'","/`v`jj''\", "`vi`jj''",.)
													}
													local cnall_post_final = subinstr("`cnall_post_final'","@","$",.)
													`q' di "`cnall_post_final'"
													
													
													`q' di "****** STATS *******"
													local snall_post_final = ""
													forvalues i = 1/`Ns' {
														`q' di `"`sc`i''"'
														local sc`i'_final = `"`sc`i''"'
														forvalues jj =1/10 {
															local sc`i'_final = subinstr(`"`sc`i'_final'"',"/`v`jj''\", "`vi`jj''",.)
														}
														local sc`i'_final = subinstr("`sc`i'_final'","@","$",.)
														
														
														`q' disp `"`sc`i'_final' --> `si`i'' -->`sn`i''"'
														`force' `q2' `sc`i'_final'
														local `sn`i'' = `si`i''
														local snall_post_final = "`snall_post_final' (``sn`i''')"
													}

													`q' di "`snall_post_final'"
													
													
													`q' di "****** POST *******"

													`q' di `"post-- `vall_post_final' `cnall_post_final' `snall_post_final' (`=`obs'') ("`command'")"'
													
													if "`force'"=="capture" & "`q'"=="qui" {
														di "----------------------------------------------------------" 
														di `"post-- `vall_post_final' `cnall_post_final' `snall_post_final' "'
														di ""
														di `" `reg_final' "'
														di ""
														}
														
													`force' local date : display %tdnn/dd/CCYY c(current_date)
													`force' local time = c(current_time)
													`force' local datetime = "`date' `time'"
													
													if `dry'!=1 `force' post `memhold' `vall_post_final' `cnall_post_final' `snall_post_final' ///
															(`=`obs'') (`" `datetime' "') (`" `command' "') 
															
													if `dry'==1 post `memhold_dry' `vall_post_final'  ///
															(`" `datetime' "') (`" `reg_final' "') 
													
												
											}
										}
									}
									
								}
							}
						}
					}
				}
			}
		}
	*/
	if `dry'!=1 `force' postclose `memhold'
	if `dry'==1 `force' postclose `memhold_dry'
	
	if "`xls'"!="no" {
		preserve
			*`force'`q2' use `rdest', clear	
			`force'`q2' use "`dataout'", clear	
				
			forvalues i=1/`Nc' {		
				`force'`q2' gen t_`cn`i'' = b_`cn`i''/se_`cn`i''
				`force'`q2' gen p_`cn`i'' = (ttail(obs,abs(t_`cn`i'')))*2
				`force'`q2' gen stars_`cn`i'' = ""
				`force'`q2' replace stars_`cn`i'' ="*" if p_`cn`i''<=.1
				`force'`q2' replace stars_`cn`i'' ="**" if p_`cn`i''<=.05
				`force'`q2' replace stars_`cn`i'' ="***" if p_`cn`i''<=.01
				local ord "`ord' b_`cn`i'' se_`cn`i'' p_`cn`i'' stars_`cn`i''" 
			}
			*`force' local date : display %tdnn/dd/CCYY c(current_date)
			*`force' local time = c(current_time)
			*`force' gen datetime = "`date' `time'"
			`force' order `vall' `ord' `snall' obs t_* datetime command
			`force' sort `vall' 

			`force' save "`dataout'" , replace
			`force' export excel "`fileout'.xlsx", sheet("`sheetout'") sheetreplace firstrow(variables) 
		restore
	}

end

******************************************************************************************************************
*TEXTABLE  --- convert results from regrunner to latex tables 
******************************************************************************************************************

**SYNTAX: textable <fileout>, results{<results file>} \\\
							* sample{<common sample restriction>} rows{<rowlist>} cols{<collist>} \\\
							* superhead{<headerinfo>} option

*fileout - location to output tex file (don't put .tex)
*results file- this is where you have saved a dataset that has the results you want to put in the table.  
*(MAKE SURE TO SAVE ALL changes to results prior to running textable: if you change vars in do file and then run textable without saving you will be calling the old version of file --> that way lies madness).
*rowlist - <varname1>["Name for Table Row", "<format>", "<font>", "<wrapper>" <, optional restriction>] <varname2>[...] ...  
*--- format is for stata, e.g. "%-4.3f"
*--- font is for latex, e.g. "it" -->\textit{}.  Can choose up to 2 fonts, e.g. itbf --> \textit{\textbf{}}
*--- wrapper is p=( ), b=[ ], ""=""
*--- optional restriction allows you to add a row-wise restriction as well (this enables multiple panels that reference different specifications/samples) 
*--- special varnames: space[] adds a blank row, line[] adds a horizontal line under previous row, title[<titlenm>,"","<font>",""] adds a row with a title in the first col and then blanks.
*collist - <Col #>[Col Name,`"Unique restriction"'] <Col #>["Col Name",`"Unique restriction"'] ... 
*--- Col Name is the title for the column, use @ to denote line breaks
*--- special col #: space[] adds a blank column
*superhead - directly input latex to go above column headers, e.g. 
*  \\ will add space between lines and headers
*  & \multicolumn{3}{c}{This is a superheader} \\ \cline{2-4} will add an underlined header above cols 2-4.
*  Be sure to get the number of cols right here.
*option - "loud" displays diagnostics ["louder" is even more detailed diagnostic--> see sample changes from individual restrictions]

*EXAMPLE:
*textable test2, sample{y=="sdr_drop"} rows{b_gtc[Eligible,%9.3f,"","s"] ///
*		se_gtc[" ",%9.3f,"","p"]  space[] obs[Obs,%9.0fc,"it",""] mean[Mean,%9.3f,"it",""] space[] line[] title[Samples:,"","itbf",""] x_frl[FRL Only,%9s,"it",""]} ///
*		cols{1[Student@FRL,pop=="frl"]  space[] 2[Student@No FRL,pop=="nofrl"]} ///
*		superhead{\\} loud

*Other Notes: 
* To create table rows that denote specifications (e.g. with Xs), create a variable with the given info in the results dataset and then use that variable in textable.
*			In the above example, textable was preceded by gen x_frl = "X" if pop=="frl".

capture program drop textable
program textable
	
	preserve
	set more off
	local 0 = subinstr(`"`0'"',char(9),"",.)
	local 0 = subinstr(`"`0'"',char(13),"",.)
	local 0 = subinstr(`"`0'"',"   ","",.)
	local input = `"`0'"'
	
	local headnums = ""
	local maxNt =0
	*****************************************************************
	*********Pull Out Options*********
	local find = regexm(`"`0'"',"(.*), +results\{(.*)\} +sample\{(.*)\} +rows\{(.*)\} +cols\{(.*)\} +superhead\{(.*)\}(.*)")
	if `find'==0 {
		di "ERROR: SYNTAX PROBLEM " as error
		if regexm(`"`0'"',"(.*),")==0 di "FILEOUT ERROR!" as error
		else {
			if regexm(`"`0'"',"(.*), +results\{(.*)\}")==0 di "RESULTS ERROR!" as error
			else {
				if regexm(`"`0'"',"(.*), +results\{(.*)\} +sample\{(.*)\}")==0 di "SAMPLE ERROR!" as error
				else {
					if regexm(`"`0'"',"(.*), +results\{(.*)\} +sample\{(.*)\} +rows\{(.*)\}")==0 di "ROWS ERROR!" as error
					else {
						if regexm(`"`0'"',"(.*), +results\{(.*)\} +sample\{(.*)\} +rows\{(.*)\} +cols\{(.*)\}")==0 di "COLS ERROR!" as error
						else {
							if regexm(`"`0'"',"(.*), +results\{(.*)\} +sample\{(.*)\} +rows\{(.*)\} +cols\{(.*)\} +superhead\{(.*)\}")==0 di "SUPERHEAD ERROR!" as error
						}
					}
				}
			}
		}
		exit
	}
	
	local fileout = regexs(1)
	local results = regexs(2)
	local sample = regexs(3)
	local rows = regexs(4)
	local cols = regexs(5)
	local shead = regexs(6)
	local ops = regexs(7)
	
	local q = "qui"
	if strmatch("`ops'","*loud*") local q = ""
	
	
	`q' di "*************************************************************"
	`q' di "**********************DIAGNOSTIC*****************************"
	`q' di "*************************************************************"
	`q' di `"sample: `sample'"'
	`q' di `"rows: `rows'"'
	`q' di `"cols: `cols'"'
	`q' di `"shead: `shead'"'
	`q' di `"fileout: `fileout'"'
	`q' di `"ops: `ops'"'
	`q' disp `"input: `input'"'
	
	if trim("`sample'")=="" local sample="1==1"
	*****************************************************************
	`q' di "********PARSE ROW**********"
	local j=1
	local rows0 = `"`rows'"'
	while strmatch(`"`rows0'"',"*[*") {
		gettoken r`j' rows0 : rows0 , parse("[")
		local rows0 = subinstr(`"`rows0'"',"[","",1)
		local stars`j' = 0
		if "`r`j''"!="space" & "`r`j''"!="line" {
			gettoken rn`j' rows0 : rows0 , parse(",")
			local rows0 = subinstr(`"`rows0'"',",","",1)
			gettoken rfmt`j' rows0 : rows0 , parse(",")
			local rows0 = subinstr(`"`rows0'"',",","",1)
			gettoken rfont`j' rows0 : rows0 , parse(",")
			local rows0 = subinstr(`"`rows0'"',",","",1)
			if strpos(`"`rows0'"',",")<strpos(`"`rows0'"',"]"){
				gettoken rwrap`j' rows0 : rows0 , parse(",")
				local rows0 = subinstr(`"`rows0'"',",","",1)
				gettoken rr`j' rows0 : rows0 , parse("]")
				local rr`j' = subinstr(`"`rr`j''"',"]","",1)
				if trim(`"`rr`j''"')!="" local rr`j' = `"& `rr`j''"'
			}
			else {
				gettoken rwrap`j' rows0 : rows0 , parse("]")
			}
			
			if strmatch("`rwrap`j''","*p*") {
				local rw0_`j' = "("
				local rw1_`j' = ")"
			}
			else if strmatch("`rwrap`j''","*b*") {
				local rw0_`j' = "["
				local rw1_`j' = "]"
			}
			
			if strmatch("`rwrap`j''","*s*") {
				local stars`j' = 1
			}
		}
		local rows0 = subinstr(`"`rows0'"',"]","",1)
		
		`q' di `"`r`j'':  Name=`rn`j''  /// Format=`rfmt`j''  /// Font=`rfont`j''  /// Wrapper=`rwrap`j'' /// Stars=`stars`j'' /// Restrict = `rr`j'' "'
		local j= `j'+1			
	}
	local Nr=`j'-1
	`q' di "N_Rows: `Nr'"
	
	*****************************************************************
	`q' di "********PARSE COL**********"
	local j=1
	local cols0 = `"`cols'"'
	while strmatch(`"`cols0'"',"*[*") {
		gettoken c`j' cols0 : cols0 , parse("[")
		local cols0 = subinstr(`"`cols0'"',"[","",1)
		if "`c`j''"!="space" {
			gettoken cn`j' cols0 : cols0 , parse(",")
			`q' di "`cn`j''"
			local h = reverse(`"`cn`j''"')+"@"
			`q' di `"`h'"'
			local jj = 1
			while strmatch(`"`h'"',"*@*") {
				gettoken hh h : h , parse("@")
				local h = subinstr(`"`h'"',"@","",1)
				local cn`j'_`jj' = reverse(`"`hh'"')
				`q' di `"`cn`j'_`jj''"'
				local jj = `jj'+1
			}
			local Nt = `jj'-1
			local maxNt = max(`Nt',`maxNt')
			
			local cols0 = subinstr(`"`cols0'"',",","",1)
			gettoken cr`j' cols0 : cols0 , parse("]")
		}
		local cols0 = subinstr(`"`cols0'"',"]","",1)
		`q' di `"`c`j'':  Name=`cn`j''  ///  Restrict=`cr`j'' "'
		local j= `j'+1			
	}
	local Nc=`j'-1
	`q' di "N_Columns: `Nc'"
	
	*****************************************************************
	local b=0
	`q' di "********LOOP THROUGH COLS-ROWS**********"
	forvalues c=1/`Nc' {
			*`q' disp `"COL: `c' (`cn`c'')--- SAMPLE: `sample'  // C Restrict: `cr`c''"'
			
			forvalues r=1/`Nr' {
				use `results', clear
				`q' count
				`q' keep if `sample'
				`q' count
				if "`c`c''"!="space" & "`r`r''"!="space" & "`r`r''"!="title" & "`r`r''"!="line" {
					`q' disp `"COL: `c' (`cn`c''), ROW: `r' (`rn`r'')  --- SAMPLE: `sample' // C Restrict: `cr`c'' // R Restrict: `rr`r'' "'
								
					if strmatch("`ops'","*louder*") {
						local restcomps = subinstr(`"`cr`c'' `rr`r''"',"&"," ",.)
						local nw_restcomps = wordcount(`" `restcomps' "')	
						forvalues wi = 1/`nw_restcomps' {
							local ww = word(`" `restcomps' "',`wi')
							di `" `wi') keep if `ww'"'
							keep if `ww'
							count
						}
					
					}
					else {
						`q' keep if `cr`c'' `rr`r''
					}
					
					qui count
					if r(N)>1 {
						disp `"ERROR: COL `c' (`cn`c'') ROW `r' (`r`r'')"' as error
						disp "RESTRICTION NOT UNIQUE, N= " r(N) as error
						disp `"Problem Restriction: `sample' & `cr`c'' `rr`r'' "' as error
						local b=1
						continue, break
					} 
					else if r(N)==0 {
						disp `"ERROR: COL `c' (`cn`c'') ROW `r' (`rn`r'')"' as error
						disp "RESTRICTION IS NOT SATISFIED, N=0" as error
						disp `"Problem Restriction: `sample' & `cr`c'' `rr`r''"' as error
						local b=1
						continue, break
						*local v_`r'_`c' = ""
					}

				}	
				if `b'==1 continue, break
				
				local rw0 = "`rw0_`r''"
				local rw1 = "`rw1_`r''"
				*`q' di "A"
				*Plug in for empty spots
				if "`r`r''"=="space" | "`r`r''"=="line" | "`r`r''"=="title" |"`c`c''"=="space" {
					local v_`r'_`c' = ""
					local rw0 = ""
					local rw1 = ""
					`q' disp "SPACE"
				}
				else { 
					confirm variable `r`r''
					local v_`r'_`c': display `rfmt`r'' `r`r''
				}
				local v_`r'_`c'= trim("`v_`r'_`c''")
				*`q' di "B"
				*Find Stars
				local s=""
				if `stars`r''==1 & "`v_`r'_`c''"!="" {
					local x = substr("`r`r''",3,.)
					local s: display stars_`x'
					local s = trim("`s'")			
				}
				*`q' di "C"
				*Set Up Fonts and Wrappers
				local rf0 = ""
				local rf1 = ""
				local rf0_2 = ""
				local rf1_2 = ""
				if "`rfont`r''"!="" {
					local rf0 = "\text"+substr(trim("`rfont`r''"),1,2)+"{"
					local rf1 = "}"
					if strlen(trim("`rfont`r''"))>2 {
						local rf0_2 = "\text"+substr(trim("`rfont`r''"),3,2)+"{"
						local rf1_2 = "}"
					}
					
				}

				*Add new value to row
				if "`v_`r'_`c''" == "" | "`v_`r'_`c''" =="." {
					local fullr`r' = "`fullr`r'' & "
				}
				else{
					if "`s'"=="" local fullr`r' = "`fullr`r'' & `rf0_2'`rf0'`rw0'`v_`r'_`c''`rw1'`rf1'`rf1_2'"
					else local fullr`r' = "`fullr`r'' & `rf0_2'`rf0'`rw0'`v_`r'_`c''`rw1'\textsuperscript{`s'}`rf1'`rf1_2'"
				}
				`q' di "`fullr`r''"
			}
			if `b'==1 continue, break
			
			*Add header name and nums to their rows
			if "`c`c''"=="space" {
				local headnums ="`headnums' & "
				forvalues jj=1/`maxNt' {
					local heads`jj' = "`heads`jj'' & "
				}
			}
			else {
				local headnums ="`headnums' & (`c`c'') "
				forvalues jj=1/`maxNt' {
					if trim("`cn`c'_`jj''")=="@" local heads`jj' = "`heads`jj'' & "
					else local heads`jj' = "`heads`jj'' & `cn`c'_`jj'' "
				}
			}
			local res_datetime = ""
			`q' capture noisily local res_datetime = datetime
	}
	
	
	*****************************************************************
	if `b'!=1{
		`q' di "********CREATE TEX FILE**********"
		local date : display %tdnn/dd/CCYY c(current_date)
		local time = c(current_time)
		`q' texdoc init "`fileout'.tex", replace force
		tex %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
		tex %OUTFILE:  `fileout' 
		tex %TABLE DATE:  `date' `time' 
		tex %RESULTS DATE: `res_datetime'
		tex %COMMAND: textable `input'
		tex %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
		tex %
		tex \begin{tabular}{l*{`Nc'}{c}}
		tex \hline \hline 
		if `"`shead'"'!="" {
			`q' di `"`shead'"'
			tex `shead'
		}
		forvalues jj=`maxNt'(-1)1 {
			`q' di `"`heads`jj''"'
			tex `heads`jj'' \\
		}
		
		`q' di `"`headnums'"'
		tex `headnums' \\ \hline \\
		forvalues r=1/`Nr' {
			local rf0 = ""
			local rf1 = ""
			local rf0_2 = ""
			local rf1_2 = ""
			if "`rfont`r''"!="" {
				local rf0 = "\text"+substr(trim("`rfont`r''"),1,2)+"{"
				local rf1 = "}"
				if strlen(trim("`rfont`r''"))>2 {
					local rf0_2 = "\text"+substr(trim("`rfont`r''"),3,2)+"{"
					local rf1_2 = "}"
				}
			}
			`q' di `"`rf0_2'`rf0'`rn`r''`rf1'`rf1_2' `fullr`r''"'
			if "`r`r''"=="line" {
				tex \hline
			}
			else if "`r`r''"=="space"{
				tex `fullr`r'' \\
			}
			else {
				tex `rf0_2'`rf0'`rn`r''`rf1'`rf1_2' `fullr`r'' \\
			}	
		}
		tex \hline \hline
		tex \end{tabular}
		texdoc close
	}
	else{
		di "PROGRAM EXIT"
	}
	restore
end
